package top.yuyufeng.mbuy.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yuyufeng.mbuy.dao.UserDao;
import top.yuyufeng.mbuy.dto.UserDTO;
import top.yuyufeng.mbuy.entity.User;
import top.yuyufeng.mbuy.exception.UserException;
import top.yuyufeng.mbuy.exception.UserExceptionEnum;
import top.yuyufeng.mbuy.service.IUserService;
import top.yuyufeng.mbuy.utils.MD5Util;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDTO checkPassword(UserDTO userDTO) throws UserException {
        User user = userDao.getByUsername(userDTO.getUsername());
        if (user == null) {
            throw new UserException(UserExceptionEnum.USER_NOT_EXITS);
        }
        if (!user.getPassword().equals(MD5Util.getMd5WithSalt(userDTO.getPassword()))) {
            throw new UserException(UserExceptionEnum.WRONG_PWD);
        }
        UserDTO result = new UserDTO();
        BeanUtils.copyProperties(user, result);
        return result;
    }

    @Override
    public UserDTO getById(int id) {
        User user = userDao.getById(id);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        return userDTO;
    }
}
